<?php

namespace app\rental\model;

use app\admin\model\RouteModel;
use app\rental\model\RentalPriceRangeModel;
use think\Model;
use think\Db;

class RentalCarModel extends Model
{
    protected $auto = ['price_range_id','price'];
    protected $type = [
        'more' => 'array',
        'primary' => 'array',
        'bodywork' => 'array',
        'engine' => 'array',
        'drive' => 'array',
        'underpan' => 'array',
    ];

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    /**
     * 关联分类表
     */
    public function categories()
    {
        return $this->belongsTo('RentalCategoryModel','category_id');
    }
    /**
     * 关联品牌表
     */
    public function brands()
    {
        return $this->belongsTo('RentalBrandModel','brand_id');
    }
    /**
     * 关联价格区间表
     */
    public function price_ranges()
    {
        return $this->belongsTo('RentalPriceRangeModel','price_range_id');
    }

    public function ranks()
    {
        return $this->belongsTo('RentalRankModel','rank_id');
    }

    public function years()
    {
        return $this->belongsTo('RentalYearModel','year_id');
    }
     public function emissions()
    {
        return $this->belongsTo('RentalEmissionModel','emission_id');
    }

    /**
     * post_content 自动转化
     * @param $value
     * @return string
     */
    public function getPostContentAttr($value)
    {
        return cmf_replace_content_file_url(htmlspecialchars_decode($value));
    }

    /**
     * post_content 自动转化
     * @param $value
     * @return string
     */
    public function setPostContentAttr($value)
    {
        return htmlspecialchars(cmf_replace_content_file_url(htmlspecialchars_decode($value), true));
    }
    public function setPriceAttr($value,$data)
    {
        return json_decode($data['primary'],true)['price'];
    }
    /**
     * price_range_id 自动完成
     */
    public function setPriceRangeIdAttr($value,$data)
    {
        $rentalPriceRangeModel = new RentalPriceRangeModel();
        $price = json_decode($data['primary'],true)['price'];
        $where['min_price'] = array('elt',$price);
        $where['max_price'] = array('egt',$price);
        $price_range_id =  $rentalPriceRangeModel->where($where)->value('id');
        if(empty($price_range_id)){
            $where['min_price'] = array('lt',$price);
            $where['max_price'] = array('eq',0);
            $price_range_id =  $rentalPriceRangeModel->where($where)->value('id');
        }
       return  $price_range_id;
    }

    /**
     * 后台管理添加文章
     * @param array $data 文章数据
     * @param array|string $categories 文章分类 id
     * @return $this
     */
    public function adminAddCar($data)
    {

        if (!empty($data['more']['thumbnail'])) {
            $data['more']['thumbnail'] = cmf_asset_relative_url($data['more']['thumbnail']);
        }

        if (!empty($data['excerpt_urls']) && !empty($data['excerpt_names'])) {
             $data['more']['excerpts'] =[];
            foreach ($data['excerpt_urls'] as $key => $url) {
                $excerptUrl = cmf_asset_relative_url($url);
                array_push($data['more']['excerpts'], ["url" => $excerptUrl, "name" => $data['excerpt_names'][$key]]);
            }
        }
        if (!empty($data['interior_urls']) && !empty($data['interior_names'])) {
             $data['more']['interiors'] =[];
            foreach ($data['interior_urls'] as $key => $url) {
                $interiorUrl = cmf_asset_relative_url($url);
                array_push($data['more']['interiors'], ["url" => $interiorUrl, "name" => $data['interior_names'][$key]]);
            }
        }
        $this->allowField(true)->data($data, true)->isUpdate(false)->save();
        return $this;

    }

    /**
     * 后台管理编辑文章
     * @param array $data 文章数据
     * @param array|string $categories 文章分类 id
     * @return $this
     */
    public function adminEditCar($data)
    {

        if (!empty($data['more']['thumbnail'])) {
            $data['more']['thumbnail'] = cmf_asset_relative_url($data['more']['thumbnail']);
        }
        if (!empty($data['excerpt_urls']) && !empty($data['excerpt_names'])) {
             $data['more']['excerpts'] =[];
            foreach ($data['excerpt_urls'] as $key => $url) {
                $excerptUrl = cmf_asset_relative_url($url);
                array_push($data['more']['excerpts'], ["url" => $excerptUrl, "name" => $data['excerpt_names'][$key]]);
            }
        }
        if (!empty($data['interior_urls']) && !empty($data['interior_names'])) {
             $data['more']['interiors'] =[];
            foreach ($data['interior_urls'] as $key => $url) {
                $interiorUrl = cmf_asset_relative_url($url);
                array_push($data['more']['interiors'], ["url" => $interiorUrl, "name" => $data['interior_names'][$key]]);
            }
        }
        $data['post_status'] = empty($data['post_status']) ? 0 : 1;
        $data['recommended'] = empty($data['recommended']) ? 0 : 1;
        $this->allowField(true)->isUpdate(true)->data($data, true)->save();
        return $this;
    }

    public function addTags($keywords, $articleId)
    {
        $portalTagModel = new PortalTagModel();

        $tagIds = [];

        $data = [];

        if (!empty($keywords)) {

            $oldTagIds = Db::name('portal_tag_post')->where('post_id', $articleId)->column('tag_id');

            foreach ($keywords as $keyword) {
                $keyword = trim($keyword);
                if (!empty($keyword)) {
                    $findTag = $portalTagModel->where('name', $keyword)->find();
                    if (empty($findTag)) {
                        $tagId = $portalTagModel->insertGetId([
                            'name' => $keyword
                        ]);
                    } else {
                        $tagId = $findTag['id'];
                    }

                    if (!in_array($tagId, $oldTagIds)) {
                        array_push($data, ['tag_id' => $tagId, 'post_id' => $articleId]);
                    }

                    array_push($tagIds, $tagId);

                }
            }


            if (empty($tagIds) && !empty($oldTagIds)) {
                Db::name('portal_tag_post')->where('post_id', $articleId)->delete();
            }

            $sameTagIds = array_intersect($oldTagIds, $tagIds);

            $shouldDeleteTagIds = array_diff($oldTagIds, $sameTagIds);

            if (!empty($shouldDeleteTagIds)) {
                Db::name('portal_tag_post')->where(['post_id' => $articleId, 'tag_id' => ['in', $shouldDeleteTagIds]])->delete();
            }

            if (!empty($data)) {
                Db::name('portal_tag_post')->insertAll($data);
            }


        } else {
            Db::name('portal_tag_post')->where('post_id', $articleId)->delete();
        }
    }

    public function adminDeletePage($data)
    {

        if (isset($data['id'])) {
            $id = $data['id']; //获取删除id

            $res = $this->where(['id' => $id])->find();

            if ($res) {
                $res = json_decode(json_encode($res), true); //转换为数组

                $recycleData = [
                    'object_id'   => $res['id'],
                    'create_time' => time(),
                    'table_name'  => 'portal_post#page',
                    'name'        => $res['post_title'],

                ];

                Db::startTrans(); //开启事务
                $transStatus = false;
                try {
                    Db::name('portal_post')->where(['id' => $id])->update([
                        'delete_time' => time()
                    ]);
                    Db::name('recycle_bin')->insert($recycleData);

                    $transStatus = true;
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {

                    // 回滚事务
                    Db::rollback();
                }
                return $transStatus;


            } else {
                return false;
            }
        } elseif (isset($data['ids'])) {
            $ids = $data['ids'];

            $res = $this->where(['id' => ['in', $ids]])
                ->select();

            if ($res) {
                $res = json_decode(json_encode($res), true);
                foreach ($res as $key => $value) {
                    $recycleData[$key]['object_id']   = $value['id'];
                    $recycleData[$key]['create_time'] = time();
                    $recycleData[$key]['table_name']  = 'portal_post';
                    $recycleData[$key]['name']        = $value['post_title'];

                }

                Db::startTrans(); //开启事务
                $transStatus = false;
                try {
                    Db::name('portal_post')->where(['id' => ['in', $ids]])
                        ->update([
                            'delete_time' => time()
                        ]);


                    Db::name('recycle_bin')->insertAll($recycleData);

                    $transStatus = true;
                    // 提交事务
                    Db::commit();

                } catch (\Exception $e) {

                    // 回滚事务
                    Db::rollback();


                }
                return $transStatus;


            } else {
                return false;
            }

        } else {
            return false;
        }
    }

    /**
     * 后台管理添加页面
     * @param array $data 页面数据
     * @return $this
     */
    public function adminAddPage($data)
    {
        $data['user_id'] = cmf_get_current_admin_id();

        if (!empty($data['more']['thumbnail'])) {
            $data['more']['thumbnail'] = cmf_asset_relative_url($data['more']['thumbnail']);
        }

        $data['post_status'] = empty($data['post_status']) ? 0 : 1;
        $data['post_type']   = 2;
        $this->allowField(true)->data($data, true)->save();

        return $this;

    }

    /**
     * 后台管理编辑页面
     * @param array $data 页面数据
     * @return $this
     */
    public function adminEditPage($data)
    {
        $data['user_id'] = cmf_get_current_admin_id();

        if (!empty($data['more']['thumbnail'])) {
            $data['more']['thumbnail'] = cmf_asset_relative_url($data['more']['thumbnail']);
        }

        $data['post_status'] = empty($data['post_status']) ? 0 : 1;
        $data['post_type']   = 2;
        $this->allowField(true)->isUpdate(true)->data($data, true)->save();

        $routeModel = new RouteModel();
        $routeModel->setRoute($data['post_alias'], 'portal/Page/index', ['id' => $data['id']], 2, 5000);

        $routeModel->getRoutes(true);
        return $this;
    }

}
